//
//  DXMLTeamObject.m
//  DerbyStatter
//
//  Created by glenn andreas on 1/6/14.
//  Copyright (c) 2014 glenn andreas. All rights reserved.
//

#import "DXMLTeamObject.h"
#import "DXMLPersonObject.h"
#import "DXMLLeagueObject.h"

@interface DXMLTeamObject()
@property (strong) NSMutableDictionary *rosterMap;
@property (strong) NSMutableArray *rosterOrder;
@end

@implementation DXMLTeamObject
- (DXMLPersonObject *) skaterForNumber: (NSString *) skaterNum create: (BOOL) createIfNeeded
{
    DXMLPersonObject *skater = [self.rosterMap objectForKey:[skaterNum uppercaseString]];
    if (!skater && createIfNeeded) {
        skater = [[DXMLPersonObject alloc] init];
        skater.number = skaterNum;
        if (!self.rosterMap) self.rosterMap = [NSMutableDictionary dictionary];
        [self.rosterMap setObject:skater forKey:[skaterNum uppercaseString]];
        if (!self.rosterOrder)
            self.rosterOrder = [NSMutableArray array];
        [self.rosterOrder addObject:skater];
        [self addChild:skater];
    }
    return skater;
}
- (void) updateRosterOrder
{
    if (self.rosterOrder.count != self.children.count) {
        NSMutableArray *roster = [NSMutableArray array];
        for (DXMLPersonObject *person in self.children) {
            if ([person isKindOfClass:[DXMLPersonObject class]]) {
                [roster addObject:person];
                [self.rosterMap setObject:person forKey:person.number];
            }
        }
        self.rosterOrder = roster;
    }
}
- (DXMLPersonObject *) skaterForIndex: (NSInteger) index
{
    [self updateRosterOrder];
    if (index < self.rosterOrder.count)
        return self.rosterOrder[index];
    return nil;
}
- (DXMLPersonObject *) skaterForSortedIndex: (NSInteger) index
{
    [self updateRosterOrder];
    if (index < self.rosterOrder.count)
        return [self skatersInSortedOrder][index];
    return nil;
}
- (NSInteger) countOfSkaters
{
    [self updateRosterOrder];
    return self.rosterOrder.count;
}
- (NSArray *) skatersInRosterOrder
{
    [self updateRosterOrder];
    return self.rosterOrder;
}
- (NSArray *) skatersInSortedOrder
{
    [self updateRosterOrder];
    return [self.rosterOrder sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [[obj1 number] compare: [obj2 number]];
    }];
}

- (void) removeChild:(DXMLObject *)child
{
    // if removing child, remove from roster map and roster order
    if ([child isKindOfClass:[DXMLPersonObject class]]) {
        DXMLPersonObject *skater = (DXMLPersonObject *) child;
        [self.rosterOrder removeObject:skater];
        [self.rosterMap removeObjectForKey:[skater.number uppercaseString]];
    }
    [super removeChild:child];
}

- (DXMLLeagueObject *) league
{
    if ([self.parent isKindOfClass:[DXMLLeagueObject class]])
        return (DXMLLeagueObject *)self.parent;
    // otherwise look up by league name
    return nil;
}
@end
